import socket
import threading
from datetime import datetime
from signal_processor import SignalProcessor

class BrainSignalReceiver:
    def __init__(self, host='127.0.0.1', port=8888):
        self.host = host
        self.port = port
        self.server_socket = None
        self.client_connection = None
        self.client_address = None
        self.running = False
        self.processor = SignalProcessor(window_size=10, threshold=0.6, key_press_duration=1.0)
        
    def start_server(self):
        """启动接收和处理服务器"""
        try:
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.server_socket.bind((self.host, self.port))
            self.server_socket.listen(1)  # 只接受一个客户端连接
            
            print(f"脑机信号接收处理器已启动在 {self.host}:{self.port}")
            print("等待发送端连接...")
            print("=" * 50)
            print("配置参数:")
            print(f"- 滑动窗口大小: {self.processor.window_size}")
            print(f"- 动作触发阈值: {self.processor.threshold}")
            print(f"- 按键持续时间: {self.processor.key_press_duration}秒")
            print(f"- 动作最小间隔: {self.processor.action_delay}秒")
            print("=" * 50)
            
            self.running = True
            
            # 接受客户端连接的线程
            accept_thread = threading.Thread(target=self.accept_connection)
            accept_thread.daemon = True
            accept_thread.start()
            
            # 等待用户输入停止服务器
            input("按回车键停止服务器...\n")
            
        except Exception as e:
            print(f"启动服务器失败: {e}")
        finally:
            self.stop_server()
    
    def accept_connection(self):
        """接受客户端连接"""
        try:
            self.client_connection, self.client_address = self.server_socket.accept()
            print(f"发送端已连接: {self.client_address}")
            
            # 开始接收和处理数据的线程
            receive_thread = threading.Thread(target=self.receive_and_process_data)
            receive_thread.daemon = True
            receive_thread.start()
            
        except Exception as e:
            if self.running:
                print(f"接受连接时发生错误: {e}")
    
    def receive_and_process_data(self):
        """接收并处理数据"""
        buffer = ""
        
        while self.running and self.client_connection:
            try:
                data = self.client_connection.recv(1024).decode('utf-8')
                if not data:
                    print("发送端连接已断开")
                    break
                    
                buffer += data
                # 处理完整指令（假设以换行符分隔）
                while '\n' in buffer:
                    line, buffer = buffer.split('\n', 1)
                    signal = line.strip()
                    
                    if signal in ['上', '下', '左', '右']:
                        timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
                        print(f"[{timestamp}] 接收: {signal}")
                        
                        # 处理信号
                        direction = self.processor.process_signal(signal)
                        if direction:
                            self.processor.execute_action(direction)
                    else:
                        print(f"警告: 收到无效信号: {signal}")
                        
            except Exception as e:
                print(f"接收处理数据错误: {e}")
                break
    
    def show_processing_status(self):
        """显示处理状态信息"""
        while self.running and self.client_connection:
            try:
                time.sleep(5)  # 每5秒显示一次状态
                if self.processor.signal_buffer:
                    buffer_size = len(self.processor.signal_buffer)
                    print(f"处理状态: 缓冲区 {buffer_size}/{self.processor.window_size} 个信号")
            except:
                break

    def stop_server(self):
        """停止服务器"""
        self.running = False
        if self.server_socket:
            self.server_socket.close()
        if self.client_connection:
            self.client_connection.close()
        print("接收处理服务器已停止")

def configure_parameters():
    """配置处理参数"""
    print("是否要配置处理参数? (y/n)")
    choice = input().strip().lower()
    
    if choice == 'y':
        try:
            window_size = int(input(f"滑动窗口大小 (默认10): ") or 10)
            threshold = float(input(f"动作触发阈值 (默认0.6): ") or 0.6)
            key_duration = float(input(f"按键持续时间(秒) (默认1.0): ") or 1.0)
            action_delay = float(input(f"动作最小间隔(秒) (默认1.0): ") or 1.0)
            
            return SignalProcessor(
                window_size=window_size,
                threshold=threshold,
                key_press_duration=key_duration,
            )
        except ValueError:
            print("输入格式错误，使用默认参数")
    
    # 返回默认处理器
    return SignalProcessor(window_size=10, threshold=0.6, key_press_duration=1.0)

if __name__ == "__main__":
    print("脑机信号接收处理器")
    print("=" * 50)
    
    # 配置处理参数
    # processor = configure_parameters()
    processor = SignalProcessor(window_size=10, threshold=0.6, key_press_duration=1.0)
    
    # 创建接收器并设置处理器
    receiver = BrainSignalReceiver()
    receiver.processor = processor
    
    # 启动服务器
    receiver.start_server()